package com.lz.ovuola.util.redis;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 
 * @author fz
 *
 */
@Component
public class RedisTemplateRepository {

	@Resource(name = "redisTemplate")
	private RedisTemplate<String, Serializable> redisTemplate;

	public void set(String nameSpace, String key, Serializable value) {
		redisTemplate.opsForValue().set(generateKey(nameSpace, key), value);
	};

	public void setEx(String nameSpace, String key, Serializable value,
			int seconds, TimeUnit unit) {
		redisTemplate.opsForValue().set(generateKey(nameSpace, key), value,
				seconds, unit);
	};

	public Serializable get(String nameSpace, String key) {
		return (Serializable) redisTemplate.opsForValue().get(
				generateKey(nameSpace, key));
	};

	public void hset(String nameSpace, String key, Serializable hashKey,
			Serializable value) {
		redisTemplate.opsForHash().put(generateKey(nameSpace, key), hashKey,
				value);
	};

	public Serializable hget(String nameSpace, String key, Serializable hashKey) {
		return (Serializable) redisTemplate.opsForHash().get(
				generateKey(nameSpace, key), hashKey);
	};

	public void del(String nameSpace, String key) {
		redisTemplate.delete(generateKey(nameSpace, key));
	}

	public void expireAt(String nameSpace, String key, Date date) {
		redisTemplate.expireAt(generateKey(nameSpace, key), date);
	}

	public void expire(String nameSpace, String key, long time, TimeUnit unit) {
		redisTemplate.expire(generateKey(nameSpace, key), time, unit);
	}

	public long lpush(String nameSpace, String key, Serializable value) {
		return redisTemplate.opsForList().leftPush(generateKey(nameSpace, key),
				value);
	};

	public long lpushAll(String nameSpace, String key, Serializable... values) {
		return redisTemplate.opsForList().leftPushAll(
				generateKey(nameSpace, key), values);
	};

	public long lpushAllByList(String nameSpace, String key,
			List<Serializable> values) {
		return redisTemplate.opsForList().leftPushAll(
				generateKey(nameSpace, key), values);
	};

	public List<Serializable> lrange(String nameSpace, String key, long start,
			long end) {
		return redisTemplate.opsForList().range(generateKey(nameSpace, key),
				start, end);
	};

	public List<Serializable> lrangeAll(String nameSpace, String key) {
		return redisTemplate.opsForList().range(generateKey(nameSpace, key), 0,
				-1);
	};

	/**
	 * 生成key
	 * 
	 * @param nameSpace
	 * @param key
	 * @return
	 */
	private String generateKey(String nameSpace, String key) {
		return new StringBuilder().append(nameSpace).append("_").append(key)
				.toString();
	}

}
